import {Goods} from "./goods.js";
import {PlaceWays} from "../enums/enum.js";
import {constants} from "../constants.js";

const {MAP_WIDTH,MAP_HEIGHT} = constants
const dis = [[1,0],[-1,0],[0,1],[0,-1]]

/**
 * 可放置的物品
 */
export class PlumableGoods extends Goods {

  /**
   * 放置方式，默认落地
   * @type {PlaceWayEnum}
   */
  placeWay = PlaceWays.FALL


  constructor(obj) {
    super(obj);
    this.placeWay = PlaceWays.valueOf(obj.placeWay)
  }

  /**
   * 默认的检查方式
   * @param arr {Uint8Array} 用于存放物块的arr
   * @param x {number}
   * @param y {number}
   * @return {boolean}
   */
  #defaultCheckCanPut = (arr, x, y) => {
    if (x<0 || y <0 || x >= MAP_WIDTH || y >= MAP_HEIGHT || arr[x][y] !== 0){
      return false
    }
    switch (this.placeWay) {
      case PlaceWays.HANG : {
        return y-1>=0 && arr[x + (y - 1) * MAP_WIDTH] !== 0
      }
      case PlaceWays.FALL : {
        return y+1 < MAP_HEIGHT && arr[x + (y + 1) * MAP_WIDTH] !== 0
      }
      case PlaceWays.CONTIGUOUS : {
        for (let d of dis) {
          let nx = x+d[0]
          let ny = y+d[1]
          if (nx>=0 && ny >=0 && nx < MAP_WIDTH && ny < MAP_HEIGHT){
            if(arr[nx + ny * MAP_WIDTH] !== 0) {
              return true
            }
          }
        }
        return false
      }
      case PlaceWays.SUSPEND_IN_AIR : {
        return true
      }
      default :
        return false
    }
  }

  /**
   *
   * 检查是否可以放置
   * @type {function(Uint8Array,number,number):boolean}
   */
  checkCanPut = this.#defaultCheckCanPut

  onclick (obj){
    const {map,x,y} = obj
    if (this.checkCanPut(map,x,y)){
      this.put(map,x,y)
    }
  }

  /**
   * 放置物品
   * @param map {Uint8Array} 要放置的地图
   * @param x {number} 横坐标
   * @param y {number} 纵坐标
   */
  put(map,x,y){
    console.error("please implements put !")
  }

  /**
   * 移除物品
   * @param map {Uint8Array}
   * @param x {number}
   * @param y {number}
   */
  remove(map,x,y) {
    console.error("please implements remove !")
  }

}